package ua.kiev.tosik.price.modules.clients.database.files;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IPricesFilesDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.Clients;

import javax.swing.*;

public class PricesFilesDeleteAllWorker extends SwingWorker<Boolean, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database.files");
	private IPricesFilesDao pricesFilesDao;
	private Clients clients;

	public PricesFilesDeleteAllWorker() {
		super();
		logger.debug("Initialize PricesFilesDeleteAllWorker");
		try {
			pricesFilesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesFilesDao();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public void setClients(Clients clients) {
		this.clients = clients;
	}

	@Override
	protected Boolean doInBackground() throws Exception {
		boolean result = false;
		firePropertyChange("FILE_DELETE_ALL_START", null, true);
		try {
			if ( clients == null ) {
				pricesFilesDao.deleteAll();
			} else {
				pricesFilesDao.deleteAll(clients);
			}
			result = true;
		}  catch (Exception e) {
			logger.error(e);
			throw new Exception(e);
		}
		firePropertyChange("FILE_DELETE_ALL_DONE", null, true);
		return result;
	}

	@Override
	protected void done() {
		super.done();
		try {
			boolean result = get();
			firePropertyChange("FILE_DELETE_ALL_OK", false, true);
		} catch (Exception e) {
			logger.error(e);
			firePropertyChange("FILE_DELETE_ALL_ERROR", null, e);
		}
	}

}
